﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using Telerik.WebControls;

using PowerCreator.LMS.DL.Project.Entity;
using PowerCreator.LMS.Web.DL.Project;
using PowerCreator.LMS.Common.Script;
using PowerCreator.LMS.Common.Utils;
using PowerCreator.LMS.Web.Course;
using PowerCreator.LMS.Course.Entity;

public partial class sysadmin_DL_Project_UserClassTasks : PowerCreator.LMS.Web.Base.WebBasePage
{
    private string classid = "0";
    private string taskid = "0";
    private string courseid = "0";
    VOTOClassTasks votask = new VOTOClassTasks();
    VOTOUserClassTask vomytask = new VOTOUserClassTask();
    TOClassTasks objtask = new TOClassTasks();
    TOUserClassTask objmytask = new TOUserClassTask();
    Course opCourse = new Course();
    VOTOCourse vocourse = new VOTOCourse();
    TOClass objclass = new TOClass();
    VOTOClass voclass = new VOTOClass();
    VOTOAccessory voaccessory = new VOTOAccessory();
    TOAccessory objaccessory = new TOAccessory();
    VOTOUserClassTask vouserclasstask = new VOTOUserClassTask();
    TOUserClassTask objuserclasstask = new TOUserClassTask();
    VOTOClassTasksReply votaskreply = new VOTOClassTasksReply();
    TOClassTasksReply objtaskReply = new TOClassTasksReply();
    VOTOLearner volearner = new VOTOLearner();
    TOLearner objlearner = new TOLearner();
    VOTOAdvancedUser voadwanceduser = new VOTOAdvancedUser();
    TOAdvancedUser objadwanceduser = new TOAdvancedUser();
    
    PowerCreator.LMS.Web.DL.User.LoginEntity login = new PowerCreator.LMS.Web.DL.User.LoginEntity();
    private string UserTask_ID = "0";
    private string TReply_Id = "0";

    protected void Page_Load(object sender, EventArgs e)
    {
        login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
        if (!IsPostBack)
        {
            ViewState["TReply_Id"] = "0";
            ViewState["faterid"] = "0";
            lbl_FileUpload_msg_FileType.Text = "注意：1、只允许上传图片类型为:rar|zip|doc|xls|ppt|txt|docx；2、上传前请先输入附件标题。 ";

            if (Request.QueryString["ClassID"] != null)
            {
                classid = Request.QueryString["ClassID"].ToString();
                ViewState["ClassID"] = classid;
                //voclass = objclass.Load(int.Parse(classid));
                //lbl_Class.Text = voclass.Name;
            }
            if (Request.QueryString["CourseID"] != null)
            {
                courseid = Request.QueryString["CourseID"].ToString();
                ViewState["CourseID"] = courseid;
                //vocourse = opCourse.LoadVOTCourse(int.Parse(courseid));
                //lbl_course.Text = vocourse.CourseName;
            }
            if (Request.QueryString["TaskID"] != null)
            {
                taskid = Request.QueryString["TaskID"].ToString();
                ViewState["TaskID"] = taskid;
                votask = objtask.Load(int.Parse(taskid));
                lbl_TaskTitle.Text = votask.TasksTitle;
                lbl_TaskContent.Text = votask.TasksContent;
                if (votask.Accessory != null)
                {
                    voaccessory = objaccessory.Load(votask.Accessory);
                    lbl_TaskAccessory.Text = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                }
                else
                {
                    lbl_TaskAccessory.Text = "无";
                }

                lbl_endtime.Text = votask.EndDate.ToString().Replace(" 0:00:00", ""); ;
                //BinderPage(lbl_endtime.Text);
            }

            if (Request.QueryString["UserTask_ID"] != null)
            {
                UserTask_ID = Request.QueryString["UserTask_ID"].ToString();
                ViewState["UserTask_ID"] = UserTask_ID;
                vouserclasstask = objuserclasstask.Load(int.Parse(UserTask_ID));
                lbl_MyTaskTitle.Text = vouserclasstask.Title;
                lbl_MyTaskContent.Text = vouserclasstask.Content;
                lbl_Finishtime.Text = vouserclasstask.CreateDate.ToString();

                if (vouserclasstask.Accessory != null)
                {
                    voaccessory = objaccessory.Load(vouserclasstask.Accessory);
                    lbl_MyTaskAccessory.Text = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                }
                else
                {
                    lbl_MyTaskAccessory.Text = "无";
                }

                volearner = objlearner.Load(vouserclasstask.Creator);
                lbl_UserName.Text = volearner.Name;

                BinderGVTeacher(int.Parse(UserTask_ID));
                BinderGVUser(int.Parse(UserTask_ID));
                BinderForm(int.Parse(UserTask_ID));
                //BinderPage(lbl_endtime.Text);
            }
        }
    }

    private void BinderGVTeacher(int id)
    {
        DataTable dt = new DataTable();
        string sql=" ReplyType=1 and UserTask_Id="+id.ToString();
        dt = objtaskReply.Query(sql);
        dt.Columns.Add("Name");
        dt.Columns.Add("AccessoryName");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            voadwanceduser=objadwanceduser.Load(int.Parse(dt.Rows[i]["Creator"].ToString()));
            dt.Rows[i]["Name"] = voadwanceduser.Name;
            if (dt.Rows[i]["Accessory"] != null)
            {
                if (dt.Rows[i]["Accessory"].ToString().Trim().Length > 0)
                {
                    voaccessory = objaccessory.Load(int.Parse(dt.Rows[i]["Accessory"].ToString()));
                    dt.Rows[i]["AccessoryName"] = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                }
                else
                {
                    dt.Rows[i]["AccessoryName"] = "无";
                }
            }
            else
            {
                dt.Rows[i]["AccessoryName"] = "无";
            }
        }
        gv_TeacherReply.DataSource = dt;
        gv_TeacherReply.DataBind();
    }

    private void BinderGVUser(int id)
    {
        DataTable dt = new DataTable();
        string sql = " ReplyType in (0,2) and UserTask_Id=" + id.ToString();
        dt = objtaskReply.Query(sql);
        dt.Columns.Add("Name");
        dt.Columns.Add("AccessoryName");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (dt.Rows[i]["ReplyType"].ToString() == "0")
            {
                volearner = objlearner.Load(int.Parse(dt.Rows[i]["Creator"].ToString()));
                dt.Rows[i]["Name"] = volearner.Name;
                if (dt.Rows[i]["Accessory"] != null)
                {
                    if (dt.Rows[i]["Accessory"].ToString().Trim().Length > 0)
                    {
                        voaccessory = objaccessory.Load(int.Parse(dt.Rows[i]["Accessory"].ToString()));
                        dt.Rows[i]["AccessoryName"] = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                    }
                    else
                    {
                        dt.Rows[i]["AccessoryName"] = "无";
                    }
                }
                else
                {
                    dt.Rows[i]["AccessoryName"] = "无";
                }
            }
            else if (dt.Rows[i]["ReplyType"].ToString() == "2")
            {
                voadwanceduser = objadwanceduser.Load(int.Parse(dt.Rows[i]["Creator"].ToString()));
                dt.Rows[i]["Name"] = voadwanceduser.Name;
                if (dt.Rows[i]["Accessory"] != null)
                {
                    if (dt.Rows[i]["Accessory"].ToString().Trim().Length > 0)
                    {
                        voaccessory = objaccessory.Load(int.Parse(dt.Rows[i]["Accessory"].ToString()));
                        dt.Rows[i]["AccessoryName"] = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                    }
                    else
                    {
                        dt.Rows[i]["AccessoryName"] = "无";
                    }
                }
                else
                {
                    dt.Rows[i]["AccessoryName"] = "无";
                }
            }
        }
        rpt_PaperReseach.DataSource = objuserclasstask.Getdtrepy(dt);
        rpt_PaperReseach.DataBind();
        //gv_UserReply.DataSource = dt;
        //gv_UserReply.DataBind();
    }




    private void BinderForm(int ID)
    {
        if (ViewState["UserTask_ID"] != null && login != null)
        {
            string search = " UserTask_Id=" + ViewState["UserTask_ID"].ToString() + " and ReplyType=1 and  Creator=" + login.UserID.ToString();
            DataTable dt = new DataTable();
            dt = objtaskReply.Query(search);
            if (dt.Rows.Count > 0)
            {
                TReply_Id = dt.Rows[0]["TReply_Id"].ToString();
                ViewState["TReply_Id"] = TReply_Id;
                txt_MyTaskContent.Text = dt.Rows[0]["Content"].ToString();
                txt_Score.Text = dt.Rows[0]["Point"].ToString();
                if (dt.Rows[0]["Accessory"] != null)
                {
                    if (dt.Rows[0]["Accessory"].ToString().Length > 0)
                    {
                        voaccessory = objaccessory.Load(int.Parse(dt.Rows[0]["Accessory"].ToString()));
                        lbl_MyAccessoryTitle.Text = "<a href=\"" + voaccessory.Url + "\" target=\"_blank\">" + voaccessory.Title + "</a>";
                        txt_MyAccessoryTitle.Text = voaccessory.Title;
                        lbl_MyAccessoryid.Text = voaccessory.Accessory_ID.ToString();
                    }

                }
            }
        }

    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        lbl_err_msg.Visible = false;
        int score = 0;
        if (!string.IsNullOrEmpty(txt_MyTaskContent.Text))
        {
            if (login != null)
            {
                //if (TReply_Id != "0")
                //    votaskreply = objtaskReply.Load(int.Parse(TReply_Id));
                try
                {
                    score = int.Parse(txt_Score.Text.Trim());
                }
                catch (Exception ex)
                {
                    lbl_err_msg.Text = "评分项必须为数字，请检查！";
                    lbl_err_msg.Visible = true;
                    return;
                }

                if (ViewState["UserTask_ID"] != null)
                {
                    votaskreply.UserTask_Id = int.Parse(ViewState["UserTask_ID"].ToString());
                    votaskreply.Content = lbl_qoen.Text.Trim() + txt_MyTaskContent.Text.Trim();
                    votaskreply.Point = score;
                    if (string.IsNullOrEmpty(lbl_qoen.Text.Trim()))
                    {
                        votaskreply.ReplyType = 1;
                        votaskreply.Trply_FaterID = 0;
                    }
                    else
                    {
                        votaskreply.ReplyType = 2;
                        votaskreply.Trply_FaterID = int.Parse(ViewState["faterid"].ToString().Trim());
                    }
                    if (lbl_MyAccessoryid.Text.Length > 0)
                        votaskreply.Accessory = int.Parse(lbl_MyAccessoryid.Text.Trim());
                    votaskreply.Creator = login.UserID;
                    votaskreply.CreateDate = DateTime.Now;
                    
                    bool b = false;
                    if (ViewState["TReply_Id"].ToString() != "0")
                    {
                        votaskreply.TReply_Id = int.Parse(ViewState["TReply_Id"].ToString());
                        b = objtaskReply.Update(votaskreply);
                    }
                    else
                        b = objtaskReply.Add(votaskreply);

                    if (b)
                    {
                        txt_MyAccessoryTitle.Text = "";
                        txt_MyTaskContent.Text = "";
                        txt_Score.Text = "";
                        lbl_MyAccessoryid.Text = "";
                        lbl_MyAccessoryTitle.Text = "";
                        BinderGVTeacher(int.Parse(ViewState["UserTask_ID"].ToString()));
                        BinderGVUser(int.Parse(ViewState["UserTask_ID"].ToString()));
                        BinderForm(int.Parse(ViewState["UserTask_ID"].ToString()));

                    }

                }
            }
        }
        else
        {
            Script.Alert("回复内容不能为空！");
        }
    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
       // btn_Back.Enabled = false;
        //Session["pwd"] = txt_UserPwd.Text;
        foreach (UploadedFile file in RadUploadContext.Current.UploadedFiles)
        {
            string Url = "";
            Url = WebUtils.WebRoot + "/fileManager/UploadFile/Accessory/";
            string Path = Server.MapPath(Url);

            //如果路径不存在，则创建
            if (System.IO.Directory.Exists(Path) == false)
            {
                System.IO.Directory.CreateDirectory(Path);
            }

            string filetype = file.GetExtension();
            if (!IsUploadFileType(filetype)) return;

            if (file.ContentLength > 10240000)
            {
                Script.Alert("上传文件不能大于10M！");
                btn_Back.Enabled = true;
                return;
            }

            //组合路径，file.GetName()取得文件名
            string fileName = opCourse.GetUploadResourceFileName(file.GetExtension());

            Path = Path + fileName;
            Url = Url + fileName;
            //保存
            file.SaveAs(Path, true);
            
            VOTOAccessory vo = new VOTOAccessory();
            TOAccessory obj = new TOAccessory();
            vo.Url = Url;
            string strTitle = txt_MyAccessoryTitle.Text.Trim();
            if (strTitle.Length == 0)
            {
                lbl_err_msg.Text = "请输入附件标题再上传！";
                lbl_err_msg.Visible = true;
                return;
            }

            if (obj.Count(" Title='" + txt_MyAccessoryTitle.Text.Trim() + "' and Url='" + Url + "' ") == 0)
            {
                int num = obj.Count(" Title like '" + txt_MyAccessoryTitle.Text.Trim() + "%' ");
                if (num > 0)
                {
                    vo.Title = txt_MyAccessoryTitle.Text.Trim() + num.ToString();
                }
                else
                {
                    vo.Title = txt_MyAccessoryTitle.Text.Trim();
                }
                vo.Createtime = DateTime.Now;
                PowerCreator.LMS.Web.Base.BasePage bpage = new PowerCreator.LMS.Web.Base.BasePage();
                vo.Creator = bpage.GetCreatedByInfo().UserID;
                int Accessory_ID = System.Int32.MinValue;
                if (obj.Add(vo, ref Accessory_ID))
                {
                    txt_MyAccessoryTitle.Text = txt_MyAccessoryTitle.Text.Trim();
                    lbl_MyAccessoryTitle.Text = "<a href=\"" + vo.Url + "\" target=\"_blank\">" + vo.Title + "</a>";

                    lbl_MyAccessoryid.Text = Accessory_ID.ToString();
                    //ListItem li = new ListItem();
                    //li.Text = vo.Title;
                    //li.Value = Accessory_ID.ToString();
                    //ddl_Accessory.Items.Insert(0, li);
                    //ddl_Accessory.ClearSelection();
                    //ddl_Accessory.SelectedValue = Accessory_ID.ToString();
                    //BinderAccessory();
                    //ddl_Accessory.SelectedValue = vo.Accessory_ID.ToString();
                }


            }
            //img_UserPic.ImageUrl = Url;
            //txt_UserPwd.Text = Session["pwd"].ToString();
            btn_Back.Enabled = true;
        }
    }

    //检查上传文件类型
    public bool IsUploadFileType(string extension)
    {
        string allowExtensions = "rar|zip|doc|xls|ppt|txt|docx";    //允许上传的类型
        if (!opCourse.IsAllowedExtension(extension, allowExtensions))
        {
            lbl_err_msg.Text = "上传文件格式不正确！<br />"+lbl_err_msg.Text;

            lbl_FileUpload_msg_FileType.Text = "格式不正确！<br />"+lbl_FileUpload_msg_FileType.Text;
            return false;
        }
        
        return true;
    }

    protected void rpt_PaperReseach_ItemCommand(object soure, RepeaterCommandEventArgs e) 
    {
        if (e.CommandName.ToString() == "Quote")
        {
            login = (PowerCreator.LMS.Web.DL.User.LoginEntity)Session[PowerCreator.LMS.Web.Config.WebConfig.SESSION_USER_USERINFO];
            ViewState["faterid"] = e.CommandArgument.ToString();
            votaskreply = objtaskReply.Load(int.Parse(e.CommandArgument.ToString()));
            string str_Quote = String.Format("&lt;div&gt; 引用：{1} 时间：{0} &lt;br/&gt;------------------------------------&lt;/div &gt;", votaskreply.CreateDate, votaskreply.Content);
            this.lbl_qoen.Text = Decode(str_Quote);
            Button1.Visible = true;
            txt_MyTaskContent.Focus();
            txt_Score.Text = "0";
            txt_Score.Enabled = false;
        }
    }
    /// <summary>
    ///解析html成 普通文本
    /// </summary>
    /// <param name="str">string</param>
    /// <returns>string</returns>
    public string Decode(string str)
    {
        str = str.Replace("<br>", "\n");
        str = str.Replace("&gt;", ">");
        str = str.Replace("&lt;", "<");
        str = str.Replace("&nbsp;", " ");
        str = str.Replace("&quot;", "\"");
        return str;
    }

    protected void btnclear_Click(object sender, EventArgs e)
    {
        lbl_qoen.Text = string.Empty;
        Button1.Visible = false;
        txt_Score.Enabled = true;
        ViewState["faterid"] = "0";
        txt_MyTaskContent.Focus();
    }

}
